package config

import (
	"encoding/json"
	"flag"
	"strings"

	"algo-sdk-go/common/apollo"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
)

type Config struct {
	RestConf    rest.RestConf
	Mongo       Mongo
	DynamicConf DynamicConf
}

type DynamicConf struct {
	Name string
}

type Mongo struct {
	Url      string
	DataBase string
}

var (
	configFile      = flag.String("f", "project/matchmaking/matchMaking-api/etc/matchmakingapi.yaml", "the config file")
	localConfigFile = flag.String("appJson", "project/matchmaking/matchMaking-api/etc/local.json", "the local config file")
)

func NewConfig() *Config {
	flag.Parse()
	apolloConfig := new(apollo.AConfig)
	conf.MustLoad(*configFile, apolloConfig)
	apolloConfig.NamespaceName = strings.Join(apolloConfig.Namespaces, ",")

	var c Config
	if apolloConfig.IsBackupConfig {
		if err := apolloConfig.Unmarshal("json", &c); err != nil {
			logx.Errorf("反序列化失败 %v", err)
		}
		// 由于 ServiceConf 只配置了 json tag 的默认值
		if bytes, err := json.Marshal(map[string]string{"Name": c.RestConf.Name}); err == nil {
			_ = conf.LoadConfigFromJsonBytes(bytes, &c.RestConf.ServiceConf)
		}
	} else {
		// 加载本地配置文件
		conf.MustLoad(*localConfigFile, &c)
	}
	return &c
}
